package com.boot2.core.web;

import com.boot2.core.SysProperties;
import com.boot2.core.exception.BusinessException;
import lombok.Data;
import lombok.extern.apachecommons.CommonsLog;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author zhangweili
 * @Description: okhttp重试请求拦截器
 * @date 2020/5/26
 */
@CommonsLog
@Data
@Component
public class OkHttpRetryIntercepter implements Interceptor {

    @Autowired
    SysProperties sysProperties;

    @Override
    public Response intercept(Chain chain) {
        int retryNum = -1;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

        Request request = chain.request();
        Response response = null;
        do {
            try {
                retryNum++;
                if (retryNum > 0) {
                    log.info("重试第【" + retryNum + "】次,request: " + request);
                }
                if (null != response) {
                    response.close();
                }
                response = chain.proceed(request);
                if (response.isSuccessful()) {
                    if (retryNum > 0) {
                        log.info("重试第【" + retryNum + "】次成功,request: " + request);
                    }
                    return response;
                }

            } catch (Exception e) {
                log.error("  请求失败,request: " + request, e);
            }
        }
        while ((response == null || !response.isSuccessful()) && retryNum < sysProperties.getHttp().getRetryCount());
        if (null == response) {
            throw new BusinessException("远程接口无法访问,url: " + request.url());
        }
        return response;
    }
}
